package com.manli.api.service;

import com.manli.api.dto.TreeApi;
import com.manli.api.dto.TreeMenu;
import com.manli.api.util.QueryParamsMapUtil;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import com.manli.api.pojo.Result;
import com.manli.api.util.ResultUtil;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import com.manli.api.dao.ViewPermissionDao;
import com.manli.api.dto.ViewPermission;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("viewPermissionService")
public class ViewPermissionService {
    @Autowired
    ViewPermissionDao viewPermissionDao;
    @Autowired
    SQLManager sqlManager;

    
    public Result queryPage(Map<String, Object> params) {
        PageQuery<ViewPermission> page = viewPermissionDao.createQuery()
                .appendSql(" where status=1 ")
                .appendSql(QueryParamsMapUtil.paramIsEmpty(params.get("permissionName"))?"":" and permission_name like '%" + params.get("permissionName") + "%'")
                .appendSql(QueryParamsMapUtil.paramIsEmpty(params.get("permissionType"))?"":" and permission_type = " + params.get("permissionType"))
                .page(Long.parseLong(params.get("page").toString()),Long.parseLong(params.get("limit").toString()));
        return ResultUtil.success(page.getList(),page.getTotalRow());
    }

    
    public Result queryAll(Map<String, Object> params) {
        List<ViewPermission> list = viewPermissionDao.createQuery().appendSql(" where status=1 ")
                .appendSql(QueryParamsMapUtil.paramIsEmpty(params.get("permissionType"))?"":" and permission_type = " + params.get("permissionType")).select();

        return ResultUtil.success(list);
    }

    
    public Result getById(Integer permissionId) {
        ViewPermission viewPermission = viewPermissionDao.single(permissionId);
        return ResultUtil.success(viewPermission);
    }

    
    public Result save(ViewPermission viewPermission) {
        viewPermissionDao.insert(viewPermission);
        return ResultUtil.success();
    }

    
    public Result updateById(ViewPermission viewPermission) {
        viewPermissionDao.updateTemplateById(viewPermission);
        return ResultUtil.success();
    }

	public Result updateTemplateById(ViewPermission viewPermission) {
        viewPermissionDao.updateTemplateById(viewPermission);
        return ResultUtil.success();
    }
    
    public Result removeById(Integer permissionId) {
        viewPermissionDao.deleteById(permissionId);
        return ResultUtil.success();
    }

    
    public Result removeByIds(List<Integer> ids) {
        for (Integer id:ids) {
            viewPermissionDao.deleteById(id);
        }
        return ResultUtil.success();
    }


    public Result treeApiAll(Map<String, Object> params) {
        if(StringUtils.isEmpty(params.get("roleId"))){
            return ResultUtil.error(-1,"roleId为空");
        }

        String sql = "select permission_id id,permission_name label from permission where permission_type = 2";
        SQLReady sqlReady = new SQLReady(sql);
        List<TreeApi> apis = sqlManager.execute(sqlReady,TreeApi.class);

        String sql2 = "select permission_id from role_permission where role_id = ?";
        SQLReady sqlReady2 = new SQLReady(sql2,params.get("roleId"));
        List<Integer> checkeds = sqlManager.execute(sqlReady2,Integer.class);

        Map map = new HashMap();
        map.put("apiData",apis);
        map.put("apiChecked",checkeds);
        return ResultUtil.success(map);
    }

    public Result treeMenuAll(Map<String, Object> params) {
        if(StringUtils.isEmpty(params.get("roleId"))){
            return ResultUtil.error(-1,"roleId为空");
        }

        String sql = "select permission_id id,permission_name label,permission_parent from permission where permission_type = 1 and is_menu = 1";
        SQLReady sqlReady = new SQLReady(sql);
        List<TreeMenu> apis = sqlManager.execute(sqlReady,TreeMenu.class);

        apis.forEach(treeMenu -> {
            List<TreeMenu> list = new ArrayList<>();
            apis.forEach(treeMenu1 -> {
                if(treeMenu1.getPermissionParent() != 0 && treeMenu.getId().intValue() == treeMenu1.getPermissionParent().intValue()){
                    list.add(treeMenu1);
                }
            });
            treeMenu.setChildren(list);
        });

        apis.removeIf(treeMenu -> {
            if(treeMenu.getPermissionParent().intValue() != 0){
                return true;
            }else{
                return false;
            }
        });

        String sql2 = "select permission_id from role_permission where role_id = ?";
        SQLReady sqlReady2 = new SQLReady(sql2,params.get("roleId"));
        List<Integer> checkeds = sqlManager.execute(sqlReady2,Integer.class);
        //未全部选中的，应该删除父节点，不然elementui-tree显示不了
        for(int i=0;i<apis.size();i++){
            if(apis.get(i).getChildren().size() > 0){
                int nums = 0;
                for(int j=0;j<apis.get(i).getChildren().size();j++){
                    for(int y=0;y<checkeds.size();y++){
                        if(checkeds.get(y).intValue() == apis.get(i).getChildren().get(j).getId().intValue()){
                            nums = nums + 1;
                        }
                    }
                }
                int id = apis.get(i).getId();
                if(nums < apis.get(i).getChildren().size()){
                    checkeds.removeIf(integer -> integer.intValue() == id);
                }
            }
        }

        Map map = new HashMap();
        map.put("menuData",apis);
        map.put("menuChecked",checkeds);
        return ResultUtil.success(map);
    }
    @Transactional
    public Result apiPermissionSave(Map<String, Object> params) {
        if(StringUtils.isEmpty(params.get("roleId"))){
            return ResultUtil.error(-1,"roleId为空");
        }

        //先删除改角色所有接口权限
        String sql2 = "delete from role_permission where role_id = ? and permission_id in (select permission_id from permission where permission_type = 2)";
        SQLReady sqlReady2 = new SQLReady(sql2,params.get("roleId"));
        sqlManager.executeUpdate(sqlReady2);

        //插入该角色最新的接口权限
        String sql3 = "insert into role_permission (role_id,permission_id) values (?,?)";
        List<Integer> pids = (List<Integer>) params.get("pids");
        pids.forEach(pid -> {
            SQLReady sqlReady3 = new SQLReady(sql3,params.get("roleId"),pid);
            sqlManager.executeUpdate(sqlReady3);
        });

        return ResultUtil.success();
    }
    @Transactional
    public Result menuPermissionSave(Map<String, Object> params) {
        if(StringUtils.isEmpty(params.get("roleId"))){
            return ResultUtil.error(-1,"roleId为空");
        }

        //先删除改角色所有菜单权限
        String sql2 = "delete from role_permission where role_id = ? and permission_id in (select permission_id from permission where permission_type = 1)";
        SQLReady sqlReady2 = new SQLReady(sql2,params.get("roleId"));
        sqlManager.executeUpdate(sqlReady2);

        //插入该角色最新的菜单权限
        String sql3 = "insert into role_permission (role_id,permission_id) values (?,?)";
        List<Integer> pids = (List<Integer>) params.get("pids");
        pids.forEach(pid -> {
            SQLReady sqlReady3 = new SQLReady(sql3,params.get("roleId"),pid);
            sqlManager.executeUpdate(sqlReady3);
        });

        return ResultUtil.success();
    }
}
